
import { existsSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
import { BasePlatform } from '../platforms/BasePlatform';
import { AutoUploadPlatform, channelToName, EPlatform, GAMEPF } from '../platforms/PlatformConfig';
import { DingdingBot } from '../utils/DingdingBot';
import { LogReport } from '../utils/LogReport';
let originPlatformId: number = 1;
export function beforeStartBuild(options: {
    channel: string,//渠道
    projectDir: string,//工程目录
    platformsInfo: any,//渠道信息
    isDebug?: boolean,//是否是测试版本
    bmsName?: string,//强制bmsname
}, callback: Function) {
    //构建前工作
    let launcherscene = path.join(options.projectDir, "assets/scene/Launcher.fire");
    if (existsSync(launcherscene)) {
        let launcher: Object[] = JSON.parse(readFileSync(launcherscene, { encoding: 'utf-8' }));
        for (let i = 0, len = launcher.length; i < len; i++) {
            let obj = launcher[i];
            if (obj.hasOwnProperty('CustomPlatform')) {
                //@ts-ignore
                originPlatformId = obj['CustomPlatform'];
                //@ts-ignore
                obj['CustomPlatform'] = EPlatform[options.channel];
                if (obj.hasOwnProperty("testMode")) {
                    //@ts-ignore
                    obj['testMode'] = !!options.isDebug;
                }

                if(obj.hasOwnProperty("remoteConfig")){
                    //@ts-ignore
                    obj['remoteConfig'] = global.remoteConfig;
                }
                if(obj.hasOwnProperty("bmsVersion")){
                    //@ts-ignore
                    obj['bmsVersion'] = global.bmsVersion;
                    //@ts-ignore
                    console.log('global.bmsVersion',obj['bmsVersion'])
                }
                writeFileSync(launcherscene, JSON.stringify(launcher, null, "\t\t"), { encoding: 'utf8' });
                break;
            }
            
        }
    } else {//另外一个配置
        let configtspath = path.join(options.projectDir, "assets/script/config/GConfig.ts");
        if (existsSync(configtspath)) {
            let configts = readFileSync(configtspath, { encoding: 'utf-8' }).toString();
            //@ts-ignore
            let curChannel = GAMEPF[options.channel];
            // if(options.bmsName){
            //     curChannel = options.bmsName;
            //     console.log("强制bms=",curChannel);
            // }
            let newp = configts.replace(/public PF = .*/, `public PF = '${curChannel}';`);
            writeFileSync(configtspath, newp, { encoding: 'utf8' });
        }
    }

    let compressFire = path.join(options.projectDir, "settings", "ccc-png-auto-compress.json");
    if (existsSync(compressFire)) {
        let compressfile: Object[] = JSON.parse(readFileSync(compressFire, { encoding: 'utf-8' }));
        //@ts-ignore
        compressfile["enabled"] = !!global.isCompress;
        writeFileSync(compressFire, JSON.stringify(compressfile, null, "\t\t"), { encoding: 'utf8' });
    }
    let ocFire = path.join(options.projectDir, "settings", "ccc-obfuscated-code.json");
    if (existsSync(ocFire)) {
        let ocssfile: Object[] = JSON.parse(readFileSync(ocFire, { encoding: 'utf-8' }));
        //@ts-ignore
        ocssfile["auto"] = !!global.isOc;
        writeFileSync(ocFire, JSON.stringify(ocssfile, null, "\t\t"), { encoding: 'utf8' });
    }
    let builder = path.join(options.projectDir, "settings","project.json");
    if(existsSync(builder) && options.platformsInfo.isNative){
        let builderFile: any = JSON.parse(readFileSync(builder, { encoding: 'utf-8' }));
        
        if(builderFile["excluded-modules"]){
            builderFile["excluded-modules"] = [
                "3D Physics/Builtin"
              ];
              writeFileSync(builder, JSON.stringify(builderFile, null, "\t\t"), { encoding: 'utf8' });
        }
        console.log(builderFile)
    }

    callback();
}

export function afterBuildFinish(options: {
    platform: BasePlatform
}, callback: Function) {
    let pl = options.platform;
    let version = pl.version;
    let channelName = channelToName[pl.curPackChannel];
    let bot = new DingdingBot(pl.configData.dingTalkWebHook);
    let gameName = pl.channelInfo.gameName ? pl.channelInfo.gameName : pl.configData.gameName;
    let outputPath = AutoUploadPlatform[pl.curPackChannel] ? (channelName + "后台") : (pl.curPackChannel == 'web_mobile'||pl.curPackChannel == 'web_desktop' ? `[${channelName}链接](${pl.channelInfo.serverPath}?_t=${Date.now()})` : pl.outputPath.substr(2));
    if (pl.curPackChannel == 'oppo' || pl.curPackChannel == 'vivo' || pl.curPackChannel == 'xiaomi' || pl.curPackChannel == 'huawei') {
        outputPath = `${outputPath}\\${pl.channelInfo.platform}\\dist\\`;
    }
    if (pl.curPackChannel.indexOf("ios") != -1 && pl.isDebug) {
        //@ts-ignore
        outputPath = `[${channelName}链接](${pl.QRCodeURL})`;
        //@ts-ignore
        version = `${version}(${pl.buildVersion})`
    }
    //@ts-ignore
    if (pl.configData.notifyDingTalk && pl.configData.dingTalkWebHook && !global.isSkipNotify) {
        let msg = `#### 游戏名字：**<font color='#1E90FF'>${gameName}</font>** \n ##### 游戏渠道：**${channelName}**\n ##### 游戏版本：**${version}** \n ##### 打包状态：**<font color='#00dd00'>完成</font>** \n ##### 资源包路径：${outputPath} \n ##### 打包时间：**${new Date().toLocaleString()}** \n`;
        let title = `${gameName}打包通知`;
        bot.pushMsgMarkdown(msg, title);
    }
    if (pl.configData.logReportUrl) {
        let reporter = new LogReport(pl.configData.logReportUrl);
        let data: any = {};
        data.name = gameName;
        data.version = version;
        data.project_team = pl.configData.teamName;
        data.source_path = outputPath;
        data.build_time = `${Math.round(Date.now() / 1000)}`;
        data.release_channel = channelName;
        if (pl.channelInfo.packageName) {
            data.pkg_name = pl.channelInfo.packageName;
        }
        reporter.postLog(data)
    }
    //构建完成后工作
    callback();
}